<!-- 后台发表文章界面 -->
<template>
  <div id="artilce">
    <div class="header">
      <Title>
        <template #title> 文章标题 </template>
      </Title>
      <input
        :style="{
          color: bgcColor.color === '#000' ? '#6e6e6e' : '#fff',
          backgroundColor:
            bgcColor.color === '#000' ? '#fff' : 'rgb(46, 46, 64)',
          borderColor:
            bgcColor.color === '#000' ? 'rgb(245, 245, 245)' : 'rgb(46, 46, 64)'
        }"
        placeholder="请输入文章标题"
        v-model.trim="state.title"
      />
    </div>
    <div class="des">
      <Title>
        <template #title> 文章简介 </template>
      </Title>
      <textarea
        :style="{
          color: bgcColor.color === '#000' ? '#6e6e6e' : '#fff',
          backgroundColor:
            bgcColor.color === '#000' ? '#fff' : 'rgb(46, 46, 64)',
          borderColor:
            bgcColor.color === '#000' ? 'rgb(245, 245, 245)' : 'rgb(46, 46, 64)'
        }"
        placeholder="请输入文章简介，若不输入，默认以文章的前100字符作为文章简介"
        v-model.trim="state.des"
      />
    </div>
    <div class="cover">
      <Title>
        <template #title> 文章封面 </template>
      </Title>
      <input
        :style="{
          color: bgcColor.color === '#000' ? '#6e6e6e' : '#fff',
          backgroundColor:
            bgcColor.color === '#000' ? '#fff' : 'rgb(46, 46, 64)',
          borderColor:
            bgcColor.color === '#000' ? 'rgb(245, 245, 245)' : 'rgb(46, 46, 64)'
        }"
        placeholder="请输入文章封面地址URL，新闻资讯可有可无，公益作用和公益记录必须有"
        v-model.trim="state.cover"
      />
    </div>
    <div class="editor">
      <Title>
        <template #title> 编辑文章 </template>
      </Title>
      <div class="editor_text">
        <Editor
          ref="EditorRef"
          :value="state.content"
          @onEditor="state.onEditor"
        />
      </div>
    </div>
    <div class="type">
      <Title>
        <template #title> 请选择文章类型 </template>
      </Title>
      <el-radio-group v-model="state.type">
        <el-radio :label="0">新闻资讯</el-radio>
        <el-radio :label="1">公益作用</el-radio>
        <el-radio :label="2">公益记录</el-radio>
      </el-radio-group>
    </div>
    <div class="submit">
      <el-button
        type="danger"
        @click="handleEmitsArticle"
        v-if="!state.articleID"
        >发表文章</el-button
      >
      <el-button type="danger" @click="handleUpdateArticle" v-else
        >更新文章</el-button
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'

import { Title, Editor } from '@/components/admin/public'

import { getArticleInfo, getEditorInfo } from '@/server/client/api_article'
import { publishArticle, updateArticleInfo } from '@/server/serve/api_article'

import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const store = useStore()

const bgcColor = computed(() => store.state.Background)
const userInfo = computed(() => store.state.userInfo)

// editor对象
const EditorRef = ref()
const state = reactive({
  // 文章id
  articleID: '',
  // 文章标题
  title: '',
  // 文章简介
  des: '',
  // 文章封面
  cover: '',
  // 文章内容
  content: '',
  // 文章类型
  type: 0,
  //获取富文本中的内容
  onEditor: (value: string) => {
    //   // console.log('父组件内容：', value)
  },
  // 富文本回显
  showBack: () => {
    // data.content = '回显内容公众号qdleader'
    setTimeout(() => {
      EditorRef.value.getContent()
    })
  }
})

// 修改文章 初始化数据
if (route.name === 'AArticle') {
  getArticleInfo(route.params.id as string).then(({ data: articleInfo }) => {
    state.articleID = articleInfo.data?.articleInfo._id!
    state.title = articleInfo.data?.articleInfo.title!
    state.des = articleInfo.data?.articleInfo.des!
    state.cover = articleInfo.data?.articleInfo.cover ?? ''
    state.type = articleInfo.data?.articleInfo.type!
    // 获取文章内容
    getEditorInfo(articleInfo.data?.articleInfo.textURL!).then(
      ({ data: editorInfo }) => {
        if (editorInfo.code) {
          router.replace('/admin')
          return ElMessage({
            type: 'warning',
            message: '该文章不存在或已被删除'
          })
        }
        state.content = editorInfo.data?.editor ?? ''
        state.showBack()
        console.log(editorInfo)
      }
    )
  })
}

onMounted(() => {
  state.showBack()
})

// 去除空格
function CTim(str: string) {
  return str.replace(/\s/g, '')
}
// 去除换行
function ClearBr(key: string) {
  key = key.replace(/<\/?.+?>/g, '')
  key = key.replace(/[\r\n]/g, '')
  return key
}

// 发表文章
const handleEmitsArticle = async () => {
  let { title, des, cover, type } = state
  if (!title.trim())
    return ElMessage({
      type: 'warning',
      message: '请输入文章标题'
    })
  if (!des.trim()) {
    des = CTim(ClearBr(EditorRef.value.editorElemBody.innerText)).slice(0, 100)
  }
  const text = EditorRef.value.editorContent
  if (!text.trim())
    return ElMessage({
      type: 'warning',
      message: '文章内容不能为空'
    })
  const { data: articleData } = await publishArticle({
    adminID: userInfo.value._id,
    title,
    des,
    cover,
    type,
    text
  })
  if (articleData.code)
    return ElMessage({
      type: 'warning',
      message: articleData.mes
    })
  // 清空
  window.location.reload()
}

// 更新文章
const handleUpdateArticle = async () => {
  let { articleID, title, des, cover, type } = state
  if (!title.trim())
    return ElMessage({
      type: 'warning',
      message: '请输入文章标题'
    })
  if (!des.trim()) {
    des = CTim(ClearBr(EditorRef.value.editorElemBody.innerText)).slice(0, 100)
  }
  const text = EditorRef.value.editorContent
  if (!text.trim())
    return ElMessage({
      type: 'warning',
      message: '文章内容不能为空'
    })
  const { data: updateResult } = await updateArticleInfo(
    articleID,
    title,
    des,
    cover,
    type,
    text
  )
  if (updateResult.code) return ElMessage.warning(updateResult.mes)
  ElMessage.success(updateResult.mes)
}
</script>

<style scoped lang="less">
#artilce {
  // background-color: #fff;
  .header {
  }
  .des {
    margin-top: 20px;
    textarea {
      margin-top: 10px;
      width: 100%;
      resize: none;
      border-radius: 16px;
      outline: none;
      border: 1px solid rgb(245, 245, 245);
      height: 100px;
      padding: 10px;
      box-sizing: border-box;
      font-size: 15px;
      color: #6e6e6e;
      &:focus {
        border: 1px solid rgb(245, 108, 108) !important;
      }
      &:hover {
        border: 1px solid rgba(245, 108, 108, 0.5) !important;
      }
    }
  }
  .cover {
    margin-top: 20px;
  }
  .editor {
    margin-top: 20px;
    min-height: 500px;
    .editor_text {
      margin-top: 20px;
    }
  }
  .submit {
    margin: 20px;
  }
  .type {
    margin-top: 20px;
  }
  input {
    margin-top: 20px;
    border-radius: 16px;
    outline: none;
    height: 42px;
    text-indent: 1em;
    display: block;
    width: 100%;
    color: #6e6e6e;
    font-size: 14px;
    box-sizing: border-box;
    border: 1px solid rgb(245, 245, 245);
    transition: all 0.3s;
    &:focus {
      border: 1px solid rgb(245, 108, 108) !important;
    }
    &:hover {
      border: 1px solid rgba(245, 108, 108, 0.5) !important;
    }
  }
}
</style>
